package com.lam.common.pay.service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayOrderQueryResult;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.constant.WxPayConstants.TradeType;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.lam.common.exception.BusinessException;
import com.lam.common.pay.vo.UnifiedOrderVo;
import com.lam.common.utils.IpUtils;
import com.lam.common.utils.JsonUtil;
import com.lam.common.utils.uuid.IdUtils;

@Service
public class LamWxPayService {
	
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
    private WxPayService wxPayService;

    public UnifiedOrderVo createWxH5Order(String payNo, BigDecimal totalFee, String orderDesc, String orderNos) {
		try {
			// 统一下单请求参数对象
			WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
			orderRequest.setNonceStr(IdUtils.getUid());
			orderRequest.setAttach(orderNos);
			orderRequest.setBody(orderDesc);
			orderRequest.setSpbillCreateIp(IpUtils.getIpAddr());// 用户终端IP:注意：用户的客户端IP，支持IPv4和IPv6两种格式的IP地址。
			
			Map<String, Object> h5Info = new HashMap<>();
			h5Info.put("type", "Wap");
			h5Info.put("wap_url", "https://lam.mall.com");
			h5Info.put("wap_name", "热潮严选");
			orderRequest.setSceneInfo(JsonUtil.toJsonString(Collections.singletonMap("h5_info", h5Info)));
			orderRequest.setOutTradeNo(payNo);
			orderRequest.setTradeType(TradeType.MWEB);
			// 回调地址
			orderRequest.setNotifyUrl(wxPayService.getConfig().getNotifyUrl());
			orderRequest.setTotalFee(totalFee.multiply(new BigDecimal(100)).intValue());
			// TradeTypeEnum 支付方式
			orderRequest.setTradeType(WxPayConstants.TradeType.Specific.MWEB.getType());
			WxPayUnifiedOrderResult result = wxPayService.unifiedOrder(orderRequest);
		    String prepayId = result.getPrepayId();
		    if (StringUtils.isBlank(prepayId)) {
		      throw new WxPayException(String.format("微信支付获取prepayId失败，错误代码： '%s'，信息：%s。",
		    		  result.getErrCode(), result.getErrCodeDes()));
		    }
			return new UnifiedOrderVo(result.getMwebUrl(), result.getMwebUrl()); //+ "&redirect_url="+wxCfg.getRedirect_url();
		} catch (Exception e) {
			logger.error("微信h5支付生成订单异常， payNo:"+payNo+", orderNos:"+orderNos, e);
			throw new BusinessException("支付订单失败");
		}
	}

	public WxPayOrderQueryResult queryTradeResult(String payNo, String tradeNo) {
		
		try {
			WxPayOrderQueryResult result = wxPayService.queryOrder(payNo, tradeNo);
			logger.info("微信H5支付结果查询，response：{}", JsonUtil.toJsonString(result));
			return result;
		} catch (Exception e) {
			logger.error("微信h5支付结果查询异常， payNo:"+payNo+", orderNos:"+tradeNo, e);
			throw new BusinessException("支付结果查询失败！");
		}
	}

}
